<template>
  <div class="product-list-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card total" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><Box /></el-icon>
            </div>
            <div class="stat-info">
              <p class="stat-label">总商品数</p>
              <p class="stat-value">{{ productList.length }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card available" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><ShoppingCart /></el-icon>
            </div>
            <div class="stat-info">
              <p class="stat-label">在售商品</p>
              <p class="stat-value">{{ availableCount }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card sold" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><Check /></el-icon>
            </div>
            <div class="stat-info">
              <p class="stat-label">已售商品</p>
              <p class="stat-value">{{ soldCount }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card reserved" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <p class="stat-label">预定商品</p>
              <p class="stat-value">{{ reservedCount }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="search-card" shadow="hover">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="在售" value="available" />
            <el-option label="已售" value="sold" />
            <el-option label="预定" value="reserved" />
            <el-option label="下架" value="removed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
        </div>
      </template>

      <el-table :data="productList" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="productId" label="ID" width="80" />
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <el-image 
              v-if="getFirstImage(row)"
              :src="getFirstImage(row)"
              :preview-src-list="[getFirstImage(row)]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 8px; cursor: pointer;"
              lazy
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" width="200" show-overflow-tooltip />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: 600; font-size: 16px;">¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="oldLevel" label="新旧程度" width="100">
          <template #default="{ row }">
            <el-tag size="small" effect="plain">{{ row.oldLevel }}成新</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creatTime" label="发布时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.creatTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row.productId)">详情</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.productId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Box, ShoppingCart, Check, Clock, Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()
const loading = ref(false)
const productList = ref([])

const searchForm = ref({
  status: ''
})

// 统计数据
const availableCount = computed(() => {
  return productList.value.filter(p => p.status === 'available').length
})

const soldCount = computed(() => {
  return productList.value.filter(p => p.status === 'sold').length
})

const reservedCount = computed(() => {
  return productList.value.filter(p => p.status === 'reserved').length
})

// 获取第一张图片
const getFirstImage = (row) => {
  if (!row.coverList) return null
  try {
    if (Array.isArray(row.coverList)) {
      return row.coverList[0] || null
    }
    if (typeof row.coverList === 'string') {
      const trimmed = row.coverList.trim()
      if (trimmed.startsWith('[')) {
        const parsed = JSON.parse(trimmed)
        return Array.isArray(parsed) ? parsed[0] : trimmed
      }
      return trimmed.split(',')[0].trim()
    }
  } catch {
    return row.coverList
  }
  return null
}

const getStatusType = (status) => {
  const types = {
    available: 'success',
    sold: 'info',
    reserved: 'warning',
    removed: 'danger'
  }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = {
    available: '在售',
    sold: '已售',
    reserved: '预定',
    removed: '下架'
  }
  return texts[status] || status
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  
  try {
    const date = new Date(dateTime)
    
    // 检查是否是有效日期
    if (isNaN(date.getTime())) {
      return dateTime
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch {
    return dateTime
  }
}

const getProductList = async () => {
  loading.value = true
  try {
    const response = await request.get('/admin/product/list', {
      params: searchForm.value
    })
    if (response.code === 0) {
      productList.value = response.data
    } else {
      ElMessage.error(response.message || '获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  getProductList()
}

const handleReset = () => {
  searchForm.value.status = ''
  getProductList()
}

const viewDetail = (productId) => {
  router.push(`/admin/product/detail/${productId}`)
}

const handleDelete = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await request.delete(`/admin/product/delete/${productId}`)

    if (response.code === 0) {
      ElMessage.success('删除成功')
      getProductList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败', error)
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  getProductList()
})
</script>

<style scoped>
.product-list-container {
  padding: 20px;
  background: #f0f2f5;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  border: none;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 70px;
  height: 70px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.stat-card.total .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card.available .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-card.sold .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-card.reserved .stat-icon {
  background: linear-gradient(135deg, #fad390 0%, #f8b500 100%);
}

.stat-info {
  flex: 1;
}

.stat-label {
  margin: 0;
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.image-slot {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 8px;
  color: #909399;
  font-size: 24px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table__header) {
  font-weight: 600;
}

@media (max-width: 768px) {
  .stat-value {
    font-size: 24px;
  }
}
</style>

